package admin

import (
	"context"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx      context.Context
	svcCtx   *svc.ServiceContext
	userRepo *mysql.UserRepo
}

// 用户列表
func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger:   logx.WithContext(ctx),
		ctx:      ctx,
		svcCtx:   svcCtx,
		userRepo: mysql.NewUserRepo(ctx, svcCtx),
	}
}

func (l *UserListLogic) UserList(req *types.UserListRequest) (*types.UserListResponse, error) {
	//根据前端传来的参数req查询用户数据列表
	userModelList, count, err := l.userRepo.GetUserListByGen2(req)
	if err != nil {
		return nil, err
	}

	//定义返回的结构体
	resp := &types.UserListResponse{
		CommonPageListResp: types.CommonPageListResp{
			Page:     req.Page,
			PageSize: req.PageSize,
			Total:    count,
		},
		List: make([]types.UserListData, 0),
	}

	//如果查询到的结果为空,直接返回预定义的空数据
	if count == 0 {
		return resp, nil
	}

	//二次处理userModelList,转换为前端需要的结构体
	for _, v := range userModelList {
		resp.List = append(resp.List, types.UserListData{
			UserId:     v.UserID,
			UserName:   v.UserName,
			Name:       v.Name,
			Age:        v.Age,
			Email:      v.Email,
			Address:    v.Address,
			Status:     v.Status,
			CreateTime: v.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return resp, nil
}

func (l *UserListLogic) GetUserCount() (count int64, err error) {
	count, err = l.userRepo.GetTotalUserCount()
	if err != nil {
		return 0, err
	}
	return count, nil
}
